package com.showdoc.controller;


import com.showdoc.mapper.TeamMapper;
import com.showdoc.mapper.TeamMemberMapper;
import com.showdoc.mapper.UserMapper;
import com.showdoc.pojo.Team;
import com.showdoc.pojo.TeamMember;
import com.showdoc.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.List;

//团队的控制层
@CrossOrigin
@RestController
@RequestMapping("team")
@EnableAutoConfiguration
public class TeamController {
    @Autowired
    private TeamMapper teamMapper;

    @Autowired
    private TeamMemberMapper teMemMapper;

    @Autowired
    private UserMapper userMapper;

    //查询所有团队的方法
    @GetMapping("/all")
    public List<Team> selectAll(){
       return teamMapper.selectAll();
    }

    //浏览用户团队信息的方法
    @GetMapping("/getList")
    public List<Team> selectByPage(HttpServletRequest request){
        Long userId = (Long) request.getSession().getAttribute("user");
        //查询当前登录用户创建的Team
        List<Team> teams = teamMapper.selectByLedID(userId);
        //查询当前用户参加的Team
        List<TeamMember> teamMembers = teMemMapper.selectByMemId(userId);
        for(TeamMember temp : teamMembers){
            Team team = teamMapper.selectById(temp.getTeamId());
            teams.add(team);
        }
        return teams;
    }

    //添加团队的方法
    @PostMapping("/save")
    public String addTeam(@RequestBody Team temp, HttpServletRequest request){
        if(teamMapper.selectByName(temp.getTeamName()) != null){
            return "该团队名称已存在，请重试...";
        }

        Long id = (Long)request.getSession().getAttribute("user");
        User user = userMapper.selectByUid(id);
        temp.setUid(id);
        temp.setUsername(user.getUsername());
        Timestamp time = new Timestamp(System.currentTimeMillis());
        temp.setAddTime(time);
        temp.setLastUpdateTime(time);
        teamMapper.save(temp);
        if(teamMapper.selectByName(temp.getTeamName()) != null){
            return "添加成功";
        }
        return "添加失败,请重试...";
    }

    //展示和登录用户有关的团队的方法

}
